/* 
 -----------------------------------------------------------------------------
                   Cogaen - Component-based Game Engine (v3)
 -----------------------------------------------------------------------------
 This software is developed by the Cogaen Development Team. Please have a 
 look at our project home page for further details: http://www.cogaen.org
    
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
 Copyright (c) 2010 Roman Divotkey

 Permission is hereby granted, free of charge, to any person obtaining a copy
 of this software and associated documentation files (the "Software"), to deal
 in the Software without restriction, including without limitation the rights
 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 copies of the Software, and to permit persons to whom the Software is
 furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in
 all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 THE SOFTWARE.
 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
*/

package org.cogaen.demo.application;

import org.cogaen.box2d.PhysicsService;
import org.cogaen.core.Core;
import org.cogaen.demo.state.CreditsState;
import org.cogaen.demo.state.GameDemoState;
import org.cogaen.demo.state.MenuState;
import org.cogaen.demo.state.PhysicsDemoState;
import org.cogaen.demo.state.SplashState;
import org.cogaen.event.EventManager;
import org.cogaen.input.InputManager;
import org.cogaen.java2d.SceneManager;
import org.cogaen.java2d.Screen;
import org.cogaen.logging.LoggingService;
import org.cogaen.resource.ResourceManager;
import org.cogaen.state.GameStateManager;
import org.cogaen.time.Clock;

public class GameApp implements Runnable {

	private double targetRate = 1.0 / 60;
	private boolean fixedDelta = false;
	private boolean frameRateGoverning = false;
	private Core core;
	private boolean endOfGame;
	
	public GameApp(Screen screen) {
		initCoreAndServices(screen);
		initGameStates();
	}
	
	private void initCoreAndServices(Screen screen) {
		this.core = Core.createCoreWithStandardServices( LoggingService.INFO );	
		this.core.installService( new InputManager( screen.getComponent() ) );
		this.core.installService( new ResourceManager() );
		this.core.installService( new SceneManager(screen) );
		this.core.installService( new PhysicsService() );
	}
	
	private void initGameStates() {
		GameStateManager stateMngr = GameStateManager.getInstance(this.core);
		stateMngr.addState( new SplashState(this.core) );
		stateMngr.addState( new CreditsState(this.core) );
		stateMngr.addState( new PhysicsDemoState(this.core, 45) );
		stateMngr.addState( new GameDemoState(this.core) );
		stateMngr.addState( new MenuState(this.core) );
		stateMngr.setCurrentState( SplashState.NAME );
		
		stateMngr.addTransition(SplashState.NAME, MenuState.NAME, SplashState.END_OF_SPLASH);
		stateMngr.addTransition(MenuState.NAME, PhysicsDemoState.NAME, MenuState.START_PHYSICS_DEMO);
		stateMngr.addTransition(MenuState.NAME, GameDemoState.NAME, MenuState.START_GAME_DEMO);
		stateMngr.addTransition(PhysicsDemoState.NAME, MenuState.NAME, PhysicsDemoState.END_OF_PHYSICS);
		stateMngr.addTransition(GameDemoState.NAME, MenuState.NAME, GameDemoState.END_OF_GAME);
		stateMngr.addTransition(MenuState.NAME, CreditsState.NAME, MenuState.END_OF_MENU);
	}
		
	public synchronized void endGame() {
		this.endOfGame = true;
	}
	
	private synchronized boolean isEndOfGame() {
		return this.endOfGame;
	}
	
	private synchronized void setEndOfGame(boolean value) {
		this.endOfGame = value;
	}
	
	@Override
	public void run() {
		setEndOfGame(false);
		Clock clock = new Clock();
		Clock upsClock = new Clock();
		SceneManager scnMngr = SceneManager.getInstance( this.core );
		PhysicsService phySrv = PhysicsService.getInstance( this.core );
		EventManager evtMngr = EventManager.getInstance( this.core );
		LoggingService logger = LoggingService.getInstance( this.core );
		
		long nsTarget = (long) (targetRate * Clock.ONE_SECOND);
		
		while (!isEndOfGame()) {
			// update clock
			clock.tick();
			upsClock.tick();
			
			// update game logic
			if (this.fixedDelta) {
				this.core.update( targetRate );
			} else {
				this.core.update( upsClock.getDelta() );
			}
			
			// update visual representation
			phySrv.syncVisibles();
			scnMngr.renderScene();
			clock.tick();

			if (this.frameRateGoverning) {
				if (clock.getNanoDelta() < nsTarget) {
					long diff = nsTarget - clock.getNanoDelta();
					long millis = diff / 1000000;
					int nanos = (int) (diff % 1000000);
					try{
						Thread.sleep(millis, nanos);
					}
					catch (InterruptedException e) {
						Thread.currentThread().interrupt();
					}
				} else {
					Thread.yield();
					logger.logDebug("GameApp", "loop cycle took to long");
				}
			} else {
				Thread.yield();				
			}
						
			// inform about current updates per seconds
			if ( upsClock.isNewUps() ) {
				evtMngr.enqueueEvent( new UpsInfoEvent( upsClock.getUps() ) );
			}
			evtMngr.enqueueEvent( new TimeInfoEvent( core.getTime() ) );
		}
	}
	
	public Core getCore() {
		return this.core;
	}

}
